package com.eds.jwt.config;

import lombok.extern.slf4j.Slf4j;
import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.jwk.RsaJwkGenerator;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@Component
public class JwtKeyConfig {
    private static final String KEY_DIR = "jwt-keys";
    private static final String PRIVATE_KEY_FILE = "private-key.json";
    private static final String PUBLIC_KEY_FILE = "public-key.json";

    private String privateKeyJson;
    private String publicKeyJson;

    @PostConstruct
    public void init() {
        try {
            createKeyDirectoryIfNotExists();
            loadOrGenerateKeys();
        } catch (Exception e) {
            log.error("初始化JWT密钥失败", e);
            throw new RuntimeException("初始化JWT密钥失败", e);
        }
    }

    private void createKeyDirectoryIfNotExists() throws IOException {
        Path keyDirPath = Paths.get(KEY_DIR);
        if (!Files.exists(keyDirPath)) {
            Files.createDirectories(keyDirPath);
            log.info("创建JWT密钥目录: {}", keyDirPath.toAbsolutePath());
        }
    }

    private void loadOrGenerateKeys() throws Exception {
        Path privateKeyPath = Paths.get(KEY_DIR, PRIVATE_KEY_FILE);
        Path publicKeyPath = Paths.get(KEY_DIR, PUBLIC_KEY_FILE);

        if (Files.exists(privateKeyPath) && Files.exists(publicKeyPath)) {
            // 加载现有密钥
            privateKeyJson = new String(Files.readAllBytes(privateKeyPath));
            publicKeyJson = new String(Files.readAllBytes(publicKeyPath));
            log.info("已加载现有JWT密钥");
        } else {
            // 生成新密钥
            RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
            privateKeyJson = rsaJsonWebKey.toJson(RsaJsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);
            publicKeyJson = rsaJsonWebKey.toJson(RsaJsonWebKey.OutputControlLevel.PUBLIC_ONLY);

            // 保存密钥到文件
            Files.write(privateKeyPath, privateKeyJson.getBytes());
            Files.write(publicKeyPath, publicKeyJson.getBytes());
            log.info("已生成并保存新的JWT密钥");
        }
    }

    public String getPrivateKeyJson() {
        return privateKeyJson;
    }

    public String getPublicKeyJson() {
        return publicKeyJson;
    }
}